/**
 * 
 */
package org.pexx.rdm.config;

import java.io.File;
import java.io.IOException;

import javax.swing.JOptionPane;


/**
 * 
 */
public class RiftConfig extends Config {

	static {
		xstream.alias("config", RiftConfig.class);		
	}
	
	protected static final String CONFIG_FILENAME = "rpkk.xml";
	
	private transient String prefix = null;

	/**
	 * 
	 */
	private RiftConfig(String prefix) {
		this.prefix = prefix;
	}
	
	private static File getFile () {
		String home = System.getProperty("user.dir");		
		return new File(home + File.separator + CONFIG_FILENAME);		
	}
	
	public static RiftConfig open (String prefix) {
		
		RiftConfig config;
		
		try {
			config = (RiftConfig) open(getFile());
			config.prefix = prefix;
		} catch (Exception e) {
			config = new RiftConfig(prefix);
			config.save();
		}
		
		return config;
			
	}
	
	public void save () {		
		try {
			save (getFile());
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, e.getLocalizedMessage(),
					"IOException", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	private String fkey (String key) {
		return prefix + "." + key;
	}
	
	@Override
	public Object getPropertie (String key, Object defaultValue) {
		Object ret = getPropertie(key);	
		
		if (ret == null) {
			ret = defaultValue;
			setPropertie (key, defaultValue);
		}
		
		return ret;
	}
	
	@Override
	public Object getPropertie (String key) {
		return super.getPropertie(fkey(key));
	}
	
	@Override
	public void setPropertie (String key, Object value) {
		super.setPropertie(fkey(key), value);
		save();
	}
}
